<template>
  <div class="member-archive-container">
    <n-grid :cols="24" :x-gap="12" style="height: calc(100vh - 150px)">
      <!-- 左侧组织机构树 -->
      <n-gi :span="6">
        <OrgTree ref="orgTreeRef" @set="handleOrgSelect" @reload="handleOrgReload" />
      </n-gi>

      <!-- 右侧人员表格 -->
      <n-gi :span="18">
        <BusTable
          ref="memberTableRef"
          :columns="columns"
          :row-key="(row) => row.memberId"
          :scroll-x="1400"
          :pagination-config="{ pageSize: 20 }"
          :search-schemas="searchSchemas"
          :form-schemas="formSchemas"
          :form-rules="rules"
          :api-methods="apiMethods"
          modal-title="人员档案管理"
          @success="handleSuccess"
          @error="handleError"
        >
          <!-- <template #tableTitle>
            <n-button type="primary" @click="handleAdd">
              <template #icon>
                <n-icon><PlusOutlined /></n-icon>
              </template>
              新增人员
            </n-button>
          </template> -->
        </BusTable>
      </n-gi>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { PlusOutlined } from '@vicons/antd';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import BusTable from '@/views/businessPages/comp/busTable/index.vue';

  // 导入API方法
  import {
    getMemberList,
    addMember,
    updateMember,
    deleteMember,
    batchDeleteMembers,
  } from '@/api/business/memberManager/member';

  const message = useMessage();
  const orgTreeRef = ref();
  const memberTableRef = ref();

  // 当前选中的组织ID
  const selectedOrgId = ref<string>('');

  // 表格列配置
  const columns = [
    {
      title: '姓名',
      key: 'memberName',
      width: 100,
      fixed: 'left',
    },
    {
      title: '性别',
      key: 'sexName',
      width: 80,
    },
    {
      title: '所属机构',
      key: 'orgName',
      width: 200,
    },
    {
      title: '机构全路径',
      key: 'orgArrayName',
      width: 300,
    },
    {
      title: '职位类型',
      key: 'postTypeName',
      width: 100,
    },
    {
      title: '人员类型',
      key: 'memberTypeName',
      width: 100,
    },
    {
      title: '在职状态',
      key: 'isPostName',
      width: 100,
    },
    {
      title: '用户名',
      key: 'userName',
      width: 120,
    },
  ];

  // 搜索表单配置
  const searchSchemas = [
    {
      field: 'memberName',
      component: 'NInput',
      label: '人员姓名',
      componentProps: {
        placeholder: '请输入人员姓名进行搜索',
      },
    },
    {
      field: 'userName',
      component: 'NInput',
      label: '用户名',
      componentProps: {
        placeholder: '请输入用户名进行搜索',
      },
    },
  ];

  // 表单配置
  const formSchemas = [
    {
      field: 'memberName',
      component: 'NInput',
      label: '人员姓名',
      placeholder: '请输入人员姓名',
      componentProps: {
        clearable: true,
      },
    },
    {
      field: 'sex',
      component: 'NSelect',
      label: '性别',
      componentProps: {
        placeholder: '请选择性别',
        options: [
          { label: '男', value: '1' },
          { label: '女', value: '2' },
        ],
      },
    },
    {
      field: 'orgId',
      component: 'NInput',
      label: '所属机构',
      placeholder: '请选择所属机构',
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'memberType',
      component: 'NSelect',
      label: '人员类型',
      componentProps: {
        placeholder: '请选择人员类型',
        options: [
          { label: '正式职工', value: '1' },
          { label: '临时工', value: '2' },
          { label: '外包人员', value: '3' },
        ],
      },
    },
    {
      field: 'isPost',
      component: 'NSelect',
      label: '在职状态',
      componentProps: {
        placeholder: '请选择在职状态',
        options: [
          { label: '在职', value: '1' },
          { label: '离职', value: '2' },
        ],
      },
    },
    {
      field: 'postType',
      component: 'NSelect',
      label: '职位类型',
      componentProps: {
        placeholder: '请选择职位类型',
        options: [
          { label: '管理', value: '1' },
          { label: '技术', value: '2' },
          { label: '操作', value: '3' },
        ],
      },
    },
    {
      field: 'userName',
      component: 'NInput',
      label: '用户名',
      placeholder: '请输入用户名',
    },
  ];

  // 表单验证规则
  const rules = {
    memberName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入人员姓名',
    },
    sex: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择性别',
    },
    orgId: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择所属机构',
    },
    userName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入用户名',
    },
  };

  // API 方法配置
  const apiMethods = {
    getList: getMemberList,
    add: addMember,
    update: updateMember,
    delete: deleteMember,
    batchDelete: batchDeleteMembers,
  };

  // 处理组织机构选择
  function handleOrgSelect(id: string, name: string) {
    selectedOrgId.value = id;
    
    // 更新表格搜索条件中的组织ID
    if (memberTableRef.value) {
      // 触发表格重新加载，传入orgId参数
      memberTableRef.value.reload({ orgId: id });
    }
  }

  // 处理组织树重新加载
  function handleOrgReload() {
    // 可以在这里添加重新加载后的逻辑
    console.log('组织树重新加载完成');
  }

  // 处理新增人员
  function handleAdd() {
    if (!selectedOrgId.value) {
      message.warning('请先选择一个组织机构');
      return;
    }

    // 设置表单中的默认组织ID
    if (memberTableRef.value) {
      memberTableRef.value.setFormModel({ orgId: selectedOrgId.value });
    }
  }

  // 处理操作成功
  function handleSuccess(operation: string) {
    const operationMap = {
      add: '新增',
      update: '编辑',
      delete: '删除',
      'batch-delete': '批量删除',
    };

    message.success(`${operationMap[operation] || operation}操作成功`);
    // 操作成功后重新加载数据，保持当前orgId过滤条件
    if (memberTableRef.value) {
      memberTableRef.value.reload({ orgId: selectedOrgId.value });
    }
  }

  // 处理操作失败
  function handleError(error: any) {
    message.error('操作失败: ' + (error.message || '未知错误'));
  }

  // 组件挂载后初始化
  onMounted(() => {
    // 可以在这里添加初始化逻辑
  });
</script>

<style scoped>
  .member-archive-container {
    padding: 16px;
    height: 100%;
    box-sizing: border-box;
  }

  :deep(.n-card) {
    height: 100%;
  }

  :deep(.n-data-table) {
    height: calc(100% - 100px);
  }
</style>